package cn.edu.sgu.www.mhxysy.service.impl;

import cn.edu.sgu.www.mhxysy.dto.UserLoginDTO;
import cn.edu.sgu.www.mhxysy.entity.User;
import cn.edu.sgu.www.mhxysy.exception.GlobalException;
import cn.edu.sgu.www.mhxysy.mapper.UserMapper;
import cn.edu.sgu.www.mhxysy.restful.ResponseCode;
import cn.edu.sgu.www.mhxysy.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

/**
 * @author heyunlin
 * @version 1.0
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

	private final HttpSession session;
	private final UserMapper userMapper;

	@Autowired
	public UserServiceImpl(HttpSession session, UserMapper userMapper) {
		this.session = session;
		this.userMapper = userMapper;
	}

	@Override
	public void logout() {
		session.removeAttribute("user");
	}

	@Override
	public void login(UserLoginDTO loginDTO) {
		String username = loginDTO.getUsername();

		QueryWrapper<User> wrapper = new QueryWrapper<>();

		wrapper.eq("username", username);

		User user = userMapper.selectOne(wrapper);

		if (user != null && user.getPassword().equals(loginDTO.getPassword())) {
			session.setAttribute("user", user);
		} else {
			throw new GlobalException(ResponseCode.FORBIDDEN, "用户名或密码错误，登录失败~");
		}
	}

	@Override
	public User getLogin() {
		Object data = session.getAttribute("user");

		if (data != null) {
			return (User) data;
		}

		return null;
	}

}